using System.Linq;
using SalesPoint.Model;
using Xtensive.Orm;
using Xtensive.Orm.Security;

namespace SalesPoint.Security
{
  public class SalesManagerRole : SalesRepresentativeRole
  {
    private static IQueryable<Order> GetOrdersQuery(ImpersonationContext context, QueryEndpoint query)
    {
      // Sales manager role has access to its own orders as well as to orders of his department
      return query.All<Order>()
        .Where(
          o =>
          o.Employee == context.Principal ||
          o.Employee.In(
            query.All<Employee>().Where(e => e.ReportsTo == context.Principal)));
    }

    protected override void RegisterPermissions()
    {
      // Sales manager inherits Sales representative permissions
      base.RegisterPermissions();

      // Sales manager can do sale orders approval, in addition
      RegisterPermission(new OrderPermission(true, true, GetOrdersQuery));
    }

    public SalesManagerRole(Session session)
      : base(session)
    {
    }
  }
}